package com.hgwz.spring.api;

import com.hgwz.spring.entity.Menu;
import com.hgwz.spring.service.MenuService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.sql.SQLOutput;
import java.util.List;

@RestController
@RequestMapping("/")
public class RestlfulAPI {
    @Resource
    private MenuService menuService;

    @GetMapping("/")
    public String healthCheck(){
        return "hi, I'm healthy!";
    }

    @GetMapping("/menus")
    public List<Menu> getAllMenus(){
        List<Menu> menus = menuService.getAllMenus();
        System.out.println(menus);
        return menus;
    }

    @PostMapping("/addmenu")
    public String addNewMenu(@RequestBody MenuBody menuBody) {
        int result = menuService.addNewMenu(menuBody.getCid(), menuBody.getMname(), menuBody.getPrice());
        System.out.println("Add menu " + result + " new menu item.");
        return "" + result;
    }

    @DeleteMapping("/delmenu")
    public String delMenu(@RequestParam(required = true) String mId){
        return "" + menuService.delMenuItem(new Integer(mId).intValue());
    }

    @GetMapping("/params")
    public String getParams(@RequestParam(required = true) String key1,
                            @RequestParam(required = false) String key2,
                            @RequestParam(required = false, defaultValue = "ThisIsDefaultValue") String key3){
        String returnString = "Key1 = " + key1 + ", Key2 = " + key2 + ", Key3 = " + key3;
        System.out.println(returnString);
        return  returnString;
    }

    @GetMapping("pathvar/{key1}/{key2}/number")
    public String getPathVariable(@PathVariable String key1, @PathVariable String key2){
        String returnString = "Key1 = " + key1 + ", Key2 = " + key2;
        System.out.println(returnString);
        return returnString;
    }

    @PostMapping("post")
    public String postMethod(@RequestBody @Valid ReqBody requestBody){
        String returnString = "Param1 = " + requestBody.getParam1() + ", Param2 = " + requestBody.getParam2();
        System.out.println(returnString);
        return returnString;
    }

    @DeleteMapping("delete")
    public String delMethod(@RequestParam(required = true) String name){
        String returnString = "The name " + name + " has been deleted!";
        System.out.println(returnString);
        return returnString;
    }

    @GetMapping("test")
    public String test(){
        String errorMsg = "An error occurs!";
        System.out.println(errorMsg);
        int i = 3/1;
        return errorMsg;
    }

}
